<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <TreeNode :data="componyInfo">
          <!-- // 方式1- 通过原型链方法控制按钮权限 -->
          <el-dropdown-item :disabled="!hasPermission('add-dept')" @click.native="onAdd(componyInfo)">添加子部门</el-dropdown-item>
        </TreeNode>
        <el-tree :data="list" :props="{ label: 'name' }" default-expand-all>
          <template v-slot="{ data }">
            <TreeNode :data="data">
              <!-- // 方式2- 通过自定义指令控制按钮权限 -->
              <el-dropdown-item v-has-perm="'add-dept'" @click.native="onAdd(data)">添加子部门</el-dropdown-item>
              <el-dropdown-item @click.native="onEdit(data)">编辑部门</el-dropdown-item>
              <el-dropdown-item @click.native="onDel(data)">删除部门</el-dropdown-item>
            </TreeNode>
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 新增部门 -->
    <!-- <AddDept :dialog-visible="dialogVisible" @closeDialog="dialogVisible = false"></AddDept> -->
    <!-- 🍑.sync语法糖：简写属性的父子通信 -->
    <AddDept ref="addDeptRef" :dialog-visible.sync="dialogVisible" :node="currentNode" @success="getDepartments"></AddDept>
  </div>
</template>

<script>
import AddDept from './components/add-dept'
import TreeNode from './components/tree-node'
import { getDepartments, delDepartments } from '@/api/departments.js'
import { translateListToTree } from '@/utils'

export default {
  name: 'DepartmentsPage',
  components: {
    AddDept,
    TreeNode
  },
  data() {
    return {
      componyInfo: { name: '传智教育', manager: '负责人', id: '' },
      list: [],
      dialogVisible: false,
      currentNode: {}
    }
  },
  created() {
    this.getDepartments()
  },
  mounted() {},
  methods: {
    async getDepartments() {
      const { companyName, depts } = await getDepartments()
      // console.log(res);
      this.componyInfo.name = companyName
      this.list = translateListToTree(depts, '')
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    onAdd(node) {
      this.dialogVisible = true
      this.currentNode = node
    },
    async onEdit({ id }) {
      await this.$refs.addDeptRef.getDepartmentDetail(id)
      // 打开对话框
      this.dialogVisible = true
    },
    onDel({ id }) {
      // 确认删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async(actions) => {
        // 调用接口
        await delDepartments(id)
        // 提示成功
        this.$message.success('删除组织架构成功')
        this.getDepartments()
      }).catch(() => { })
      // 刷新
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
